<template>
  <div class="app-container">
  <!--站点数据-->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="选择校区" prop="schoolId">
       <el-select v-model="queryParams.schoolId" placeholder="请选择" clearable filterable size="small" @keyup.enter.native="handleQuery" >
         <el-option
           v-for="dict in schoolOptions"
           :key="dict.value"
           :label="dict.name"
           :value="dict.id"
         />
       </el-select>
      </el-form-item>
      <el-form-item label="注册时间" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="用户状态"
          clearable
          size="small"
        >
          <el-option :key="999" :label="'全部'" :value="null" />
           <el-option :key="0" :label="'正常'" :value="0" />
           <el-option :key="1" :label="'冻结中'" :value="1" />
           <el-option :key="2" :label="'已拉黑'" :value="2" />
           <el-option :key="3" :label="'已注销'" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:user:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
        >导出</el-button> -->
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="mobile" width="110px" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="所属校区" align="center" prop="schoolName" />
      <el-table-column label="历史发单" align="center" prop="totalCount" />
      <el-table-column label="最后一次登录时间" align="center" prop="lastLoginTime" width="130px" />
      <el-table-column label="最后一次发单时间" align="center" prop="lastIssueTime" width="130px" />
      <el-table-column label="注册时间" align="center" prop="createTime" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <span>{{ cuserState(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row, '详情')"
          >详情</el-button>
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="success"
            @click="handleThaw(scope.row)"
          >解冻</el-button>
          <el-button
            v-if="scope.row.status !== 2"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >拉黑</el-button>
          <el-button
            v-if="scope.row.status === 2"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >取消拉黑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详细 -->
    <el-dialog title="详细" :visible.sync="detailOpen" width="600px">
      <el-form ref="form" :model="form" label-width="120px" size="mini">
        <el-row>
          <el-col :span="8">
            <el-form-item label="历史发单数：">{{ form.totalCount }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态：">{{ cuserState(form.status) }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="姓名：">{{ form.name }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="微信昵称：">{{ form.nickName }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="手机号：">{{ form.mobile }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="绑定微信：">{{ form.openId }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="年龄：">{{ form.age }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="性别：">{{ form.sex === '0' ? '男':'女' }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="所属校区：">{{ form.schoolName }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="注册时间：">{{ form.createTime }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="最后一次登录时间：">{{ form.lastLoginTime }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="最后一次发单时间：">{{ form.lastIssueTime }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { exportUser } from "@/api/system/user";
import { listCuser,saveOrUpdateCuser,blackCuser,unBlackCuser } from "@/api/pt/cuser.js";
import { listSchool } from "@/api/pt/school.js";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { areajson } from "@/utils/area.js";

export default {
  name: "Cuser",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 已有校区所在城市数据
      ownCity: [],
      // 已有校区数据
      schoolOptions: [],
      // 城市数据
      cityOptions: areajson,
      // 表单参数
      form: {
      },
      //详情打开
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        schoolId: undefined,
        mobile: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "站点名称不能为空", trigger: "blur" }
        ],
        schoolId: [
          { required: true, message: "请选择校区", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        time: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();

    listSchool({pageNum: 1,pageSize: 10000}).then(response => {
      let list = response.data.list
      let lArr = ''
      let listArr = []
      list.map(item=>{
        if(lArr.indexOf(item.city) == -1) {
          lArr += ',' + item.city
        }
      })
      lArr = lArr.split(',')
      lArr.map(item=>{
        listArr.push({
          label: item ? item : '全部',
          value: item
        })
      })
      this.schoolOptions = response.data.list
      this.ownCity = listArr
    });
  },
  methods: {
    /* 用户状态 */
    cuserState(str){
      if(str === 0) {
        return '正常'
      }else if(str === 1) {
        return '冻结中'
      }else if(str === 2) {
        return '已拉黑'
      }else if(str === 3) {
        return '已注销'
      }
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listCuser(this.addDateRange2(this.queryParams)).then(response => {
          this.userList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === 0 ? "启用" : "关闭";
      this.$confirm('确认要' + text + '"' + row.name + '"吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          row.time = [new Date(row.startTime),new Date(row.endTime)]
          return addSchool(row)
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
      this.form = {
        id: undefined,
        schoolId: undefined,
        name: undefined,
        city: undefined,
        status: undefined,
        address: undefined,
        siteDescribe: undefined,
        personInCharge: undefined,
        mobile: undefined,
        personInCharge2: undefined,
        mobile2: undefined,
        time: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      console.log(row)
      this.title = "修改";
      row.time = [new Date(row.startTime),new Date(row.endTime)]
      this.form = row
      if(type === '详情') {
        this.detailOpen = true;
      }else {
        this.open = true;
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row)
      const Ids = row.id || this.ids;
      let text = ''
     if(row.status === 2){
        text = `是否取消拉黑"${row.name}"客户？`
        this.$confirm(text, "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          console.log(123123)
          console.log(Ids)
          console.log(unBlackCuser)
          return unBlackCuser(Ids)
        }).then(() => {
          this.getList();
          this.msgSuccess("修改成功");
        }).catch(function() {});
      }else {
        text = `是否确认拉黑"${row.name}"客户？`
        this.$prompt('请输入拉黑理由', "拉黑理由", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(({ value }) => {
          let pa = {
            msg: value
          }
          return blackCuser(Ids,pa)
        }).then(() => {
          this.getList();
          this.msgSuccess("修改成功");
        }).catch(function() {});
      }

    },
    /** 修改按钮操作 */
    handleThaw(row, type) {
      let pa = {
        status: 0,
        id: row.id || this.ids,
      }
      this.$confirm(`是否确认解冻"${row.name}"客户？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return saveOrUpdateCuser(pa);
      }).then(() => {
        this.getList();
        this.msgSuccess("修改成功");
      }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.fileDownload(response.data, "用户管理.xlsx");
        }).catch(function() {});
    },

    // 获取当前选中校区所在城市
    selectSchool(val) {
      this.schoolOptions.map(item=>{
        if(item.id === val) this.form.city = item.city
      })
    }
  }
};
</script>

<style type="text/css">
  .dian {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    display: inline-block;
    background: #999;
    margin-right: 6px;
  }
</style>
